<?php

/**
 * Return contacts in a folder or all contacts for
 * contact list.
 * 
 * @author Volker Kueffel <volker.kueffel@gmail.com>
 * @version $Id: get_contacts.php 18 2009-01-05 02:18:30Z volker.kueffel $
 */

require_once('config.php');
require_once('LDAPConnector.class.php');
require_once('Utils.class.php');

$ldap=LDAPConnector::init($config);

$result=new StdClass();
$result->data=array();
$result->success=false;
$result->numResults=0;
if ($ldap) {
	
	$dn='';
	if (array_key_exists('subdn',$_REQUEST) && $_REQUEST['subdn']) {
		$dn=$ldap->getFullDN($_REQUEST['subdn']);
	} else {
		$dn=$ldap->getBaseDN();
	}

	$fields=array();
	$listOnly=false;
	if (!array_key_exists('full',$_REQUEST) || $_REQUEST['full']!=1) {
		$fields=array('sn','givenname','mail','cn');
		$listOnly=true;
	}
	$results=$ldap->query($dn,'(objectClass=inetOrgPerson)',$fields);
	if (is_array($results)) {
		$levels=count(split(',',$dn))+1; // we usually only want everything below request DN
		$ignoreLevel=(array_key_exists('showall',$_REQUEST) && $_REQUEST['showall']==1) || (array_key_exists('full',$_REQUEST) && $_REQUEST['full']==1);
		foreach ($results as $entry) {
			//['lastname','firstname','email','subdn'],
			if (is_array($entry) && ($ignoreLevel || count(split(',',$entry['dn']))==$levels)) {
				if (array_key_exists('objectclass',$entry)) unset($entry['objectclass']);		
				$entry['subdn']=$listOnly ? $ldap->extractSubDN($entry['dn'],$dn) : $ldap->extractSubDN($entry['dn']);
				unset($entry['dn']);			
				$contact=Utils::array2Object($entry);
				$result->data[]=$contact;
				$result->success=true;
			}
		}
		$result->numResults=count($result->data);
	}
}
if (array_key_exists('single',$_REQUEST) && $_REQUEST['single']==1) {
	$results=$result->data;
	if (count($results)>=1) {
		$result->data=$results[0];
		$result->numResults=1;
	} 
}
echo json_encode($result);
?>